import { http } from 'jindai-api'
import { BASE_URL } from '@/http/config'

const url = 'admin/attachments'

export const fetchList = (params) => http.get(url, { params })

export const getMultimediaUri = (type) => {
  return `${BASE_URL}/upload`
}

export const upload = ({ type = 'avatar', file, progress }) => {
  const form = new FormData()
  const xhr = new XMLHttpRequest()
  return new Promise((resolve, reject) => {
    form.append('type', type)
    form.append('file', file)
    xhr.withCredentials = true
    xhr.open('POST', getMultimediaUri(type), true)
    xhr.onload = (e) => {
      if (xhr.status < 200 || xhr.status >= 300) {
        reject(new Error(12))
      } else {
        const data = JSON.parse(e.target.responseText)
        resolve(data.data)
      }
    }
    xhr.onerror = (e) => {
      reject(e)
    }
    if (progress) {
      xhr.upload.onprogress = (e) => {
        if (e.total > 0) {
          progress((e.loaded / e.total) * 100)
        }
      }
    }
    xhr.send(form)
  })
}

export const uploadAttachments = async (type, files, simditor, progress) => {
  const data = [];
  for (let i = files.length - 1; i >= 0; i -= 1) {
    data.push(await upload({ type, file: files.item(i), simditor, progress }));
  }
  return data.reverse();
};